package com.ht.api.call.func.impl.customer;

import cn.hutool.core.util.StrUtil;
import com.ht.api.bean.AjaxResult;
import com.ht.api.bean.LoginBean;
import com.ht.api.call.func.IFunctionCall;
import com.ht.api.db.Db;
import com.ht.api.db.DbList;
import com.ht.api.db.DbPage;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ht.api.db.Entity;

import java.util.ArrayList;
import java.util.List;

/**
 * 客户聊天信息查询
 * @author asq
 * @createTime 2025年3月26日 19:03:19
 */
public class WwxCustomerMsgQueryFunctionCall implements IFunctionCall {

	@Override
	public String getName() {
		return "客户聊天信息查询";
	}

	@Override
	public JSONObject execute(LoginBean me, JSONObject param, AjaxResult result) {
		int pageNum = param.getInt("pagenum");
		int pageSize = param.getInt("pagesize");
		int pageStart = (pageNum - 1) * pageSize;

		String userid = param.getStr("userid");
		String externalUserid = param.getStr("external_userid");
		String oneid = param.getStr("oneid");
		if (StrUtil.isBlank(externalUserid) && StrUtil.isNotBlank(oneid)) {
			externalUserid = Db.createSqlParser("user_origin").select("openid").where("oneid", oneid).limit(1).val(me.getDataSource());
		}

		StringBuilder sql = new StringBuilder();
		sql.append("select * from wx_msg where isroom = 0 ");
		sql.append("and ((`from` = ? and touser = ?) or (`from` = ? and touser = ?)) ");

		long total = Db.count(me.getDataSource(), "select sum(sys_deleted) from (" + sql.toString() + ") t ", userid, externalUserid, externalUserid, userid);
		sql.append("order by msgtime desc ");

		sql.append("limit ?,?");
		DbList list = Db.query(me.getDataSource(), sql.toString(), userid, externalUserid, externalUserid, userid, pageStart, pageSize);

		for (Entity msg : list) {
			int fromUsertype = 2;
			String from = msg.getStr("from");
			Entity user = Db.createSqlParser("wx_workuser").select("alias aliasname,avatar,gender,name").where("userid", from).findOne(me.getDataSource());

			if (user == null) {
				String usersql = "select oneid,nickname,aliasname,avatar,gender from user_main where status = 0 and bitmap_contains(users, "+Math.abs(from.hashCode())+")";
				user = Db.findOne(me.getDataSource(), usersql);
				fromUsertype = 1;
			}
			msg.set("from_user_type", fromUsertype);
			msg.set("mapper_from", user);
		}

		// 构造分页对象
		DbPage dbPage = DbPage.builder()
		        .pagenum(pageNum)
		        .pagesize(pageSize)
		        .total(total)
		        .record(list)
		        .build();
		return JSONUtil.createObj().set("list", dbPage);
	}

}
